package com.zitronella.course.osseventmanager.service;

import com.zitronella.course.osseventmanager.domain.Event;
import com.zitronella.course.osseventmanager.domain.Position;
import com.zitronella.course.osseventmanager.domain.Volunteer;
import com.zitronella.course.osseventmanager.exception.PositionFilledException;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import java.util.List;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: Robin
 * Date: Feb 28, 2009
 * Time: 4:06:23 PM
 * To change this template use File | Settings | File Templates.
 */
public class VolunteerServiceImpl implements VolunteerService{

    private EntityManagerFactory entityManagerFactory;
    EntityManager em;


    /**
     *
     * @param entityManagerFactory
     */
    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }

    /**
     *
     * @return
     */
    public EntityManager getEntityManager(){

        return entityManagerFactory.createEntityManager();
    }


    


    //v6
    @SuppressWarnings("unchecked")
    public boolean registerEventUserForPosition(String eventName, String positionName, String userEmail){

        EntityManager em = entityManagerFactory.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        Volunteer volunteer = new Volunteer(eventName, positionName, userEmail);
        try {
            //Get Event
            Query query = em.createQuery("select distinct(i) from Event i where i.name = ?");
            query.setParameter(1, eventName);

            Event e = (Event)query.getSingleResult();
            
            //Get Position
            Query query1 = em.createQuery("select distinct(p) from Position p where p.name = ?");
            query1.setParameter(1, positionName);
            Position p = (Position)query1.getSingleResult();
            if(p.getNoOfVolunteerOpenPosition()> 0){
                this.fillPosition(p);
                tx.begin();
                em.persist(volunteer);
                tx.commit();
            }else{
                throw new PositionFilledException("Position " + p.getName() + " is Filled");
            }
            return true;

        }catch(RuntimeException e){
            if (tx != null && tx.isActive())
                tx.rollback();
            throw e;
        } finally {
            em.close();
        }
    }
    @SuppressWarnings("unchecked")
    public void fillPosition(Position p){

        EntityManager em = entityManagerFactory.createEntityManager();
        EntityTransaction tx = em.getTransaction();

        int total = p.getNoOfVolunteerPositionReq();
        int currentFilled = p.getNoOfVolunteerFilledPosition();
        p.setNoOfVolunteerFilledPosition(++currentFilled);
        int currentOpen = p.getNoOfVolunteerOpenPosition();
        p.setNoOfVolunteerOpenPosition(--currentOpen);

        try {
            tx.begin();
            em.merge(p);
            tx.commit();
        } catch (RuntimeException x) {
            if (tx != null && tx.isActive())
                tx.rollback();
            throw x;
        } finally {
            em.close();
        }

    }

    //v6
    @SuppressWarnings("unchecked")
    public boolean unRegisterEventUserForPosition(String eventName, String positionName, String userEmail){

        EntityManager em = entityManagerFactory.createEntityManager();
        EntityTransaction tx = em.getTransaction();

        try {
            //Get Event
            Query query = em.createQuery("select distinct(v) from  Volunteer v where v.eventName = ? and v.positionName = ? and v.userEmail = ?");
            query.setParameter(1, eventName);
            query.setParameter(2, positionName);
            query.setParameter(3, userEmail);
            List<Volunteer> vList = query.getResultList();
            Volunteer volunteer = vList.get(1);
            //Get Position
            Query query1 = em.createQuery("select distinct(p) from Position p where p.name = ?");
            query1.setParameter(1, positionName);
            Position p = (Position)query1.getSingleResult();

            if(p.getNoOfVolunteerFilledPosition() > 0){
                this.unfillPositions(p);
                tx.begin();
                em.remove(volunteer);
                tx.commit();
            }else{
                return false;
            }
            return true;

        }catch(RuntimeException e){
            if (tx != null && tx.isActive())
                tx.rollback();
            throw e;
        } finally {
            em.close();
        }
    }


    public void unfillPositions(Position p){
        EntityManager em = entityManagerFactory.createEntityManager();
        EntityTransaction tx = em.getTransaction();

        int total = p.getNoOfVolunteerPositionReq();
        int currentFilled = p.getNoOfVolunteerFilledPosition();
        System.out.println ("Current Filled" + currentFilled);
        p.setNoOfVolunteerFilledPosition(--currentFilled);
        int currentOpen = p.getNoOfVolunteerOpenPosition();
        p.setNoOfVolunteerOpenPosition(++currentOpen);

        try {
            tx.begin();
            em.merge(p);
            tx.commit();
        } catch (RuntimeException x) {
            if (tx != null && tx.isActive())
                tx.rollback();
            throw x;
        } finally {
            em.close();
        }
    }

}
